/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.exception.logger;

import io.iec.edp.caf.commons.runtime.CafEnvironment;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Leon Huo
 */
@Slf4j
public class ExceptionInnerLogger {
    private static String path = getLogPath();

    private static String getLogPath() {
        return CafEnvironment.getServerRTPath() + "/log/logException";
    }

    private static Lock lock = new ReentrantLock();

    public static void writeLog(Exception exception, String title) {
        lock.lock();
        try {
            var error = "";
            if (exception != null) error = exception + System.lineSeparator();
            if (error.isEmpty()) return;

            //创建文件目录
            String path = ExceptionInnerLogger.path;
            File fileDirectory = new File(path);
            if (!fileDirectory.exists()) {
                boolean success = fileDirectory.mkdirs();
                if (!success) throw new CafInnerLogException("file system error", null);
            }
            //文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String logName = String.format("CAFRuntimeException%s.log", sdf.format(new Date()));
            String fileName = path + "/" + logName;

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(fileName, true);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
                bufferedWriter.write("=====================================================================================");
                bufferedWriter.write('\n');
                bufferedWriter.write(title == null ? "" : title);
                bufferedWriter.write('\n');
                SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                bufferedWriter.write(String.format("记录时间%s", sdff.format(new Date())));
                bufferedWriter.write('\n');
                bufferedWriter.write(String.format("信息文本%s", error));
                bufferedWriter.write('\n');
                bufferedWriter.write("调用堆栈信息如下");
                bufferedWriter.write('\n');
                bufferedWriter.write(ExceptionUtils.getStackTrace(exception));
                bufferedWriter.flush();
                bufferedWriter.close();
            } catch (IOException e) {
                log.error("Log Inner Exception Error !", e);
            }
        } finally {
            lock.unlock();
        }
    }
}
